﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using DataBaseLibrary.DBInterfaces;
using System.ComponentModel;

namespace DataBaseLibrary.DBObjectsFB
{


    public class Individual : DBFObject, IDBObject, INotifyPropertyChanged, IDataErrorInfo
    {


        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, e);
        }

        private int m_Address = 0;

        public IndividualAddress Address
        {
            get;
            set;
        }

        String m_CitizenShip = "";
        public string CitizenShip
        {
            get
            {
                return m_CitizenShip;
            }
            set
            {
                m_CitizenShip = value;
                OnPropertyChanged(new PropertyChangedEventArgs("CitizenShip"));
            }
        }

        DateTime? m_DateOfBirth = null;
        public DateTime? DateOfBirth
        {
            get { return m_DateOfBirth; }
            set
            {
                m_DateOfBirth = value;
                OnPropertyChanged(new PropertyChangedEventArgs("DateOfBirth"));
            }
        }

        String m_EMail = "";
        public string EMail
        {
            get
            {
                return m_EMail;
            }
            set
            {
                
                m_EMail = value;
                OnPropertyChanged(new PropertyChangedEventArgs("EMail"));
            }
        }

        String m_FirstName = "";
        public string FirstName
        {
            get
            {
                return m_FirstName;
            }
            set
            {
                m_FirstName = value;
                OnPropertyChanged(new PropertyChangedEventArgs("FirstName"));
            }
        }

        String m_LastName = "";
        public string LastName
        {
            get
            {
                return m_LastName;
            }
            set
            {
                m_LastName = value;
                OnPropertyChanged(new PropertyChangedEventArgs("LastName"));
            }
        }
        private int m_oInsuranceCompany = 0;

        public InsuranceCompany OInsuranceCompany
        {
            get;
            set;
        }

        private DateTime? m_PassportDateIssue = null;
        public DateTime? PassportDateIssue
        {
            get
            {
                return m_PassportDateIssue;
            }
            set
            {
                m_PassportDateIssue = value;
                OnPropertyChanged(new PropertyChangedEventArgs("PassportDateIssue"));
            }
        }

        private String m_PassportIssuedBy = "";
        public string PassportIssuedBy
        {
            get
            {
                return m_PassportIssuedBy;
            }
            set
            {
                OnPropertyChanged(new PropertyChangedEventArgs("PassportIssuedBy"));
                m_PassportIssuedBy = value;
            }
        }

        private String m_PassportNumber = "";
        public string PassportNumber
        {
            get
            {
                return m_PassportNumber;
            }
            set
            {
                m_PassportNumber = value;
                OnPropertyChanged(new PropertyChangedEventArgs("PassportNumber"));
            }
        }

        private String m_PassportSeries = "";
        public string PassportSeries
        {
            get
            {
                return m_PassportSeries;
            }
            set
            {
                m_PassportSeries = value;
                OnPropertyChanged(new PropertyChangedEventArgs("PassportSeries"));
            }
        }

        private String m_Patronymic = "";
        public string Patronymic
        {
            get
            {
                return m_Patronymic;
            }
            set
            {
                m_Patronymic = value;
                OnPropertyChanged(new PropertyChangedEventArgs("Patronymic"));
            }
        }

        private String m_PhoneNumber = "";
        public string PhoneNumber
        {
            get
            {
                return m_PhoneNumber;
            }
            set
            {
                m_PhoneNumber = value;
                OnPropertyChanged(new PropertyChangedEventArgs("PhoneNumber"));
            }
        }

        private String m_Sex = "";
        public string Sex
        {
            get
            {
                return m_Sex;
            }
            set
            {
                m_Sex = value;
                OnPropertyChanged(new PropertyChangedEventArgs("Sex"));
            }
        }

        private String m_TIN = "";
        public string TIN
        {
            get
            {
                return m_TIN;
            }

            set
            {
                m_TIN = value;
                OnPropertyChanged(new PropertyChangedEventArgs("TIN"));
            }
        }


        public Individual()
        {
            NameTable = "INDIVIDUAL_TABLE";
            Address = new IndividualAddress();
            OInsuranceCompany = new InsuranceCompany();

            CitizenShip = ""; 
            DateOfBirth = null;  
            EMail = ""; 
            FirstName = ""; 
            LastName = "";  
            PassportDateIssue = null; 
            PassportIssuedBy = "";  
            PassportNumber = "";
            PassportSeries = ""; 
            Patronymic = ""; 
            PhoneNumber = ""; 
            Sex = "Муж"; 
            TIN = "";

        }

        object IDBObject.Save()
        {
            try
            {
                Parameters = new Dictionary<string, object>();

                Parameters.Add("ID_ADDRESS", (Address as IDBObject).Save());
                Parameters.Add("ID_INSURANCE_COMPANY", (OInsuranceCompany as IDBObject).Save());

                Parameters.Add("CITIZENSHIP", CitizenShip);
                Parameters.Add("DATE_OF_BIRTH", DateOfBirth);
                Parameters.Add("E_MAIL", EMail);
                Parameters.Add("FIRST_NAME", FirstName);
                Parameters.Add("LAST_NAME", LastName);
                Parameters.Add("PASSPORT_DATE_ISSUE", PassportDateIssue);
                Parameters.Add("PASSPORT_ISSUED_BY", PassportIssuedBy);
                Parameters.Add("PASSPORT_NUMBER", PassportNumber);
                Parameters.Add("PASSPORT_SERIES", PassportSeries);
                Parameters.Add("PATRONYMIC", Patronymic);
                Parameters.Add("PHONE_NUMBER", PhoneNumber);
                Parameters.Add("SEX", Sex);
                Parameters.Add("TIN", TIN);


                return SaveObject();
            }
            catch (SystemException errException)
            {
                throw new SystemException(String.Format("Ошибка при сохранении объекта {0} в БД:\n {1}", this.ToString(), errException.Message));
            }
        }

        void IDBObject.Load(object ID)
        {
            try
            {

                Parameters = new Dictionary<string, object>();
                Parameters.Add("ID_ADDRESS", m_Address);
                Parameters.Add("ID_INSURANCE_COMPANY", m_oInsuranceCompany);

                Parameters.Add("CITIZENSHIP", CitizenShip);
                Parameters.Add("DATE_OF_BIRTH", DateOfBirth);
                Parameters.Add("E_MAIL", EMail);
                Parameters.Add("FIRST_NAME", FirstName);
                Parameters.Add("LAST_NAME", LastName);
                Parameters.Add("PASSPORT_DATE_ISSUE", PassportDateIssue);
                Parameters.Add("PASSPORT_ISSUED_BY", PassportIssuedBy);
                Parameters.Add("PASSPORT_NUMBER", PassportNumber);
                Parameters.Add("PASSPORT_SERIES", PassportSeries);
                Parameters.Add("PATRONYMIC", Patronymic);
                Parameters.Add("PHONE_NUMBER", PhoneNumber);
                Parameters.Add("SEX", Sex);
                Parameters.Add("TIN", TIN);

                LoadObject(ID);
                ((Address = new IndividualAddress()) as IDBObject).Load(Parameters["ID_ADDRESS"]);
                ((OInsuranceCompany = new InsuranceCompany()) as IDBObject).Load(Parameters["ID_INSURANCE_COMPANY"]);

                CitizenShip = (String)Parameters["CITIZENSHIP"].ToString();
                DateOfBirth = Parameters["DATE_OF_BIRTH"] == null || Parameters["DATE_OF_BIRTH"].ToString() == String.Empty? (DateTime?)null : DateTime.Parse(Parameters["DATE_OF_BIRTH"].ToString());
                EMail = (String)Parameters["E_MAIL"].ToString();
                FirstName = (String)Parameters["FIRST_NAME"].ToString();
                LastName = (String)Parameters["LAST_NAME"].ToString();
                PassportDateIssue = Parameters["PASSPORT_DATE_ISSUE"] == null || Parameters["PASSPORT_DATE_ISSUE"].ToString() == String.Empty ? (DateTime?)null : DateTime.Parse(Parameters["PASSPORT_DATE_ISSUE"].ToString());
                PassportIssuedBy = (String)Parameters["PASSPORT_ISSUED_BY"].ToString();
                PassportNumber = (String)Parameters["PASSPORT_NUMBER"].ToString();
                PassportSeries = (String)Parameters["PASSPORT_SERIES"].ToString();
                Patronymic = (String)Parameters["PATRONYMIC"].ToString();
                PhoneNumber = (String)Parameters["PHONE_NUMBER"].ToString();
                Sex = (String)Parameters["SEX"].ToString();
                TIN = (String)Parameters["TIN"].ToString();

            }
            catch (SystemException err)
            {
                throw new SystemException(String.Format("Ошибка при загрузке объекта {0} в БД \n {1}", this, err.Message));
            }
        }


        void IDBObject.Update()
        {
            (Address as IDBObject).Update();
            (OInsuranceCompany as IDBObject).Update();

            Parameters = new Dictionary<string, object>();
            Parameters.Add("CITIZENSHIP", CitizenShip);
            Parameters.Add("DATE_OF_BIRTH", DateOfBirth);
            Parameters.Add("E_MAIL", EMail);
            Parameters.Add("FIRST_NAME",  FirstName);
            Parameters.Add("LAST_NAME", LastName);
            Parameters.Add("PASSPORT_DATE_ISSUE", PassportDateIssue);
            Parameters.Add("PASSPORT_ISSUED_BY", PassportIssuedBy);
            Parameters.Add("PASSPORT_NUMBER", PassportNumber);
            Parameters.Add("PASSPORT_SERIES", PassportSeries);
            Parameters.Add("PATRONYMIC", Patronymic);
            Parameters.Add("PHONE_NUMBER", PhoneNumber);
            Parameters.Add("SEX", Sex);
            Parameters.Add("TIN", TIN);

            UpdateObject();

        }

        public string this[string columnName]
        {
            get { return Validate(columnName); }
        }

        public string Error
        {
            get { return "Ошибка ввода!"; }
            private set { }

        }

        private string Validate(string properyName)
        {
            
            string validationMessgae = String.Empty;
            switch (properyName)
            {
                case "EMail":                    
                    validationMessgae = ValidationEmail();
                    break;
            }
            return validationMessgae;
        }

        //Валидация поля e-mail
        private string ValidationEmail()
        {
            if (m_EMail == null || m_EMail.Equals(String.Empty))
                return String.Empty;
            string validEmailPattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
            + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
            + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";

            bool isValid = (new Regex(validEmailPattern, RegexOptions.IgnoreCase)).IsMatch(m_EMail);
            if (!isValid)
                return "Неверно введен e-mail!";
            return String.Empty;
        }

    }
}
